package br.com.canvasForAll.model.services;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Collection;
import java.util.Date;

import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.inject.Named;
import javax.ws.rs.core.MultivaluedMap;

import br.com.canvasForAll.model.entity.Arquivo;
import br.com.canvasForAll.model.entity.Postit;
import br.com.canvasForAll.model.repository.ArquivoRepository;
import br.com.canvasForAll.model.services.interfaces.ArquivoService;
import br.com.canvasForAll.model.utils.StringUtil;

@Stateless
@Named("arquivoService")
public class ArquivoServiceImpl implements ArquivoService {
	
	@EJB private ArquivoRepository arquivoRepository;
	
	@Override
	public Collection<Arquivo> obterArquivoPostit(Postit postit) throws Exception {
		return arquivoRepository.obterArquivoPostit(postit);
	}

	@Override
	public String getFileName(MultivaluedMap<String, String> header) throws Exception {
		String[] contentDisposition = header.getFirst("Content-Disposition").split(";");
		
		for(String filename : contentDisposition){
			if((filename.trim().startsWith("filename"))){
				String[] name = filename.split("=");
				String finalFileName = name[1].trim().replaceAll("\"", "");
				String ext = finalFileName.substring(finalFileName.lastIndexOf('.') + 1);
				finalFileName = StringUtil.gerarHash(finalFileName.replace("." + ext, "") + String.valueOf(new Date().getTime())) + "." + ext;
				
				return finalFileName;
			}
		}
		return "unknown";
	}
	
	@Override
	public void writeFile(byte[] content, String filename) throws IOException {
		File file = new File(filename);

		if (!file.exists())
			file.createNewFile();
 
		FileOutputStream fileOutStream = new FileOutputStream(file);
		fileOutStream.write(content);
		fileOutStream.flush();
		fileOutStream.close();
	}

	@Override
	public Arquivo salvarArquivo(Arquivo a) throws Exception {
		return arquivoRepository.criar(a);
	}

}
